package lc.q150_200;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class Q166 {

    public static void main(String[] args) {
        Q166 q166 = new Q166();
        System.out.println(q166.fractionToDecimal(-1,-2147483648));
    }

    public String fractionToDecimal(int numerator, int denominator) {
        // 变成long就不会有问题了
        long numeratorLong = numerator;
        long denominatorLong = denominator;
        boolean isNeg = (numerator < 0 && denominator > 0) || (numerator > 0 && denominator < 0);
        numeratorLong = Math.abs(numeratorLong);
        denominatorLong = Math.abs(denominatorLong);
        String fh = isNeg ? "-":"";
        long intPart = numeratorLong / denominatorLong;
        StringBuilder smallPart = new StringBuilder();
        Map<Long, Integer> checked = new HashMap<>();
        int i = 0;
        while (numeratorLong % denominatorLong != 0) {
            numeratorLong = (numeratorLong % denominatorLong) * 10;
            if (checked.containsKey(numeratorLong)) {
                // 找到循环地址了，拼上
                return fh + intPart + "." + smallPart.substring(0, checked.get(numeratorLong)) + "(" + smallPart.substring(checked.get(numeratorLong), smallPart.length()) + ")";
            }
            checked.put(numeratorLong,  i ++);
            smallPart.append(numeratorLong / denominatorLong);
        }
        if (smallPart.length() == 0) {
            return fh + intPart + "";
        } else {
            return fh + intPart + "." + smallPart.toString();
        }
    }
}
